package com.zhijian.warehouse.manage.util;

import com.zhijian.util.AssertUtil;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.StringWriter;
import java.io.Writer;
import java.util.Collections;

public class FreemarkerUtil {
    private static final Logger log = LoggerFactory.getLogger(FreemarkerUtil.class);

    public FreemarkerUtil() {
    }

    public static Configuration getConfig(String templatePath) {
        Configuration config = new Configuration(Configuration.VERSION_2_3_28);
        config.setClassForTemplateLoading(FreemarkerUtil.class, templatePath);
        config.setDefaultEncoding("UTF-8");
        config.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
        return config;
    }

    public static String generateAsString(Object data, String templatePath, String templateName) {
        log.info("Freemarker:HTML::start generate html string {}", templatePath);

        try {
            Configuration config = getConfig(templatePath);
            Template template = config.getTemplate(templateName);
            Writer out = new StringWriter();

            String var6;
            try {
                template.process(data, out);
                log.info("Freemarker:HTML::generate html string success, {}", templatePath);
                var6 = out.toString();
            } finally {
                if (Collections.singletonList(out).get(0) != null) {
                    ((Writer) out).close();
                }
            }
            return var6;
        } catch (Exception var11) {
            log.info("Freemarker:HTML::generate html string exception, {}", templatePath, var11);
            AssertUtil.notNull(null, "Freemarker:HTML::generate html string exception, {}", templatePath);
        }
        return null;
    }
}
